import type { Router, LocationQueryRaw } from 'vue-router';
import NProgress from 'nprogress'; // progress bar
import { Message } from '@arco-design/web-vue';
import { useUserStore } from '@/store';
import { isLogin, setToken, clearToken } from '@/utils/auth';
import { jumpLogin } from '@/api/hairdryer';

export default function setupUserLoginInfoGuard(router: Router) {
  router.beforeEach(async (to, from, next) => {
    NProgress.start();
    const userStore = useUserStore();

    console.log(isLogin());
    console.log(userStore.role);
    
    // 当URL中带有Authorization参数时清除token
    if (to.query.Authorization) {
      clearToken();
      console.log('检测到Authorization参数，已清除现有token');
    }
    
    


    if (isLogin()) {
      // 恢复正常的权限控制逻辑，允许用户访问其他页面
      if (userStore.role) {
        next();
      } else {
        try {
          
          await userStore.info();
          next();
          
        } catch (error) {
          await userStore.logout();
          next({
            name: 'login',
            query: {
              redirect: to.name,
              ...to.query,
            } as LocationQueryRaw,
          });
        }
      }
    } else {
      // 检查是否已处理过URL中的Authorization参数，避免死循环
      const isProcessingAuth = sessionStorage.getItem('isProcessingAuth');
      // 获取当前重试次数
      const authAttemptCount = sessionStorage.getItem('authAttemptCount');
      const attemptCount = authAttemptCount ? parseInt(authAttemptCount, 10) : 0;
      // 最大重试次数
      const MAX_ATTEMPTS = 2;
      
      // 检查URL中是否有Authorization参数且没有正在处理认证，且未超过重试次数
      if (!isProcessingAuth && to.query.Authorization && attemptCount < MAX_ATTEMPTS) {
        try {
          // 标记正在处理认证，避免死循环
          sessionStorage.setItem('isProcessingAuth', 'true');
          // 增加重试计数
          sessionStorage.setItem('authAttemptCount', (attemptCount + 1).toString());
          
          // 提取Authorization参数中的token部分，保留从bearer开始的完整token
          const authToken = to.query.Authorization as string;
          // 调用jumpLogin接口获取token
          const response = await jumpLogin({ token: authToken });
          
          // 保存token到localStorage
          setToken(response.data.token);
          
          
          // 清除处理认证的标记和重试计数
          sessionStorage.removeItem('isProcessingAuth');
          sessionStorage.removeItem('authAttemptCount');
          
          // 构建新的路由对象，保留path和hash，但清除query中的Authorization参数
          // const newQuery = { ...to.query };
          // delete newQuery.Authorization;
          
          // 认证成功后直接跳转到订单记录页面
          next({
            name: 'UsageRecord',
            replace: true
          });
        } catch (error) {
          console.error('从URL获取认证信息失败:', error);
          // 清除处理认证的标记，保留重试计数
          sessionStorage.removeItem('isProcessingAuth');
          
          // 如果已达到最大重试次数
          if (attemptCount + 1 >= MAX_ATTEMPTS) {
            Message.error('认证失败次数过多，请稍后重试');
            sessionStorage.removeItem('authAttemptCount');
            // 跳转到登录页并移除Authorization参数，避免再次尝试
            const newQuery = { ...to.query };
            delete newQuery.Authorization;
            next({
              name: 'login',
              query: {
                redirect: to.name,
                ...newQuery,
              } as LocationQueryRaw,
            });
          } else {
            Message.error('从URL获取认证信息失败，请重新登录');
            next({
              name: 'login',
              query: {
                redirect: to.name,
                ...to.query,
              } as LocationQueryRaw,
            });
          }
        }
      } else if (to.name === 'login') {
        // 清除处理认证的标记和重试计数
        sessionStorage.removeItem('isProcessingAuth');
        sessionStorage.removeItem('authAttemptCount');
        next();
        return;
      } else {
        // 如果达到最大重试次数，直接跳转到登录页并移除Authorization参数
        if (attemptCount >= MAX_ATTEMPTS && to.query.Authorization) {
          const newQuery = { ...to.query };
          delete newQuery.Authorization;
          next({
            name: 'login',
            query: {
              redirect: to.name,
              ...newQuery,
            } as LocationQueryRaw,
          });
        } else {
          next({
            name: 'login',
            query: {
              redirect: to.name,
              ...to.query,
            } as LocationQueryRaw,
          });
        }
      }
    }
  });
}
